import Layout from "@/layout"; // 引入Layout
import router from './router'
import store from '@/store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { Message } from 'element-ui'
import getPageTitle from '@/utils/get-page-title'
import { getToken } from '@/utils/auth' // get token from cookie
const whiteList = ['/login'] // no redirect whitelist

// 路由拦截器
router.beforeEach(async (to, from, next) => {
  // 进度条加载
  NProgress.start();
  document.title = getPageTitle(to.meta.title);
  // 获取token决定用户是否可以登录
  const hasToken = getToken();
  if (hasToken) {
    if (to.path === "/login") {
      next({ path: "/" });
      NProgress.done();
    } else {
      const hasGetUserInfo = store.getters.menus && store.getters.menus.length > 0
      if (hasGetUserInfo) {
        next();
      } else {
        try {
          const { menus } = await store.dispatch("user/getInfo");
          const accessRoutes = await store.dispatch('permission/generateRoutes', menus);
          // 404页面，通配符一定要最后添加
          accessRoutes.push({
            path: "/404", component: () => import('@/views/404.vue'), hidden: "true"
          }, {
            path: "*",
            redirect: "/404",
            hidden: "true",
          })
          router.addRoutes(accessRoutes);
          next({ ...to, replace: true });
        } catch (error) {
          await store.dispatch("user/resetToken");
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      }
    }
  } else {
    /* 没有token */
    if (whiteList.indexOf(to.path) !== -1) {
      // 如果该路由在白名单内, 放行
      next();
    } else {
      // 不在白名单内不允许通过重定向到登录页
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done()
})

